package com.xomily.devops.service.impl;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xomily.common.utils.Arith;
import com.xomily.common.utils.ip.IpUtils;
import com.xomily.devops.domain.dashboard.Dashboard;
import com.xomily.devops.domain.dashboard.DevCpu;
import com.xomily.devops.domain.dashboard.DevJvm;
import com.xomily.devops.domain.dashboard.DevMem;
import com.xomily.devops.domain.dashboard.DevSys;
import com.xomily.devops.domain.dashboard.DevSysFile;
import com.xomily.devops.domain.dashboard.Devops;
import com.xomily.devops.mapper.DevAlarmMapper;
import com.xomily.devops.mapper.DevCpuLogMapper;
import com.xomily.devops.mapper.DevHostMapper;
import com.xomily.devops.service.IDevDashboardService;


import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.hardware.CentralProcessor.TickType;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;
import oshi.util.Util;

import com.xomily.common.utils.CommonUtil;
import com.xomily.common.utils.DateUtils;

/**
 * 控制台Service业务层处理
 * 
 * @author xomily
 * @date 2021-12-27
 */
@Service
public class DevDashboardServiceImpl implements IDevDashboardService {

	private static final int OSHI_WAIT_SECOND = 1000;
	
	
	@Autowired
	private DevHostMapper hostMapper;
    @Autowired
    private DevCpuLogMapper cpuLogMapper;
    @Autowired
    private DevAlarmMapper alarmMapper;

	/**
	 * 设置主控面板信息
	 * 
	 * @param 无
	 * @return 状态码
	 */
	@Override
	public Dashboard getDashboardInfo() throws Exception {
		Dashboard dashboard = new Dashboard();

		SystemInfo si = new SystemInfo();
		HardwareAbstractionLayer hal = si.getHardware();

		dashboard.setCpu(getCpuInfo(hal.getProcessor()));
		dashboard.setMem(getMemInfo(hal.getMemory()));
		dashboard.setSys(getSysInfo());
		dashboard.setJvm(getJvmInfo());
		dashboard.setSysFiles(getSysFiles(si.getOperatingSystem()));
		dashboard.setDevops(getDevopsInfo());

		return dashboard;
	}

	/**
	 * 设置CPU信息
	 */
	private DevCpu getCpuInfo(CentralProcessor processor) {
		DevCpu cpu = new DevCpu();
		// CPU信息
		long[] prevTicks = processor.getSystemCpuLoadTicks();
		Util.sleep(OSHI_WAIT_SECOND);
		long[] ticks = processor.getSystemCpuLoadTicks();
		long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()];
		long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()];
		long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()];
		long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()];
		long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];
		long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()];
		long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];
		long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];
		long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;
		cpu.setCpuNum(processor.getLogicalProcessorCount());
		cpu.setTotal(totalCpu);
		cpu.setSys(cSys);
		cpu.setUsed(user);
		cpu.setWait(iowait);
		cpu.setFree(idle);
		return cpu;
	}

	/**
	 * 设置内存信息
	 */
	private DevMem getMemInfo(GlobalMemory memory) {
		DevMem mem = new DevMem();
		mem.setTotal(memory.getTotal());
		mem.setUsed(memory.getTotal() - memory.getAvailable());
		mem.setFree(memory.getAvailable());
		return mem;
	}

	/**
	 * 设置服务器信息
	 */
	private DevSys getSysInfo() {
		DevSys sys = new DevSys();
		Properties props = System.getProperties();
		sys.setComputerName(IpUtils.getHostName());
		sys.setComputerIp(IpUtils.getHostIp());
		sys.setOsName(props.getProperty("os.name"));
		sys.setOsArch(props.getProperty("os.arch"));
		sys.setUserDir(props.getProperty("user.dir"));
		return sys;
	}

	/**
	 * 设置Java虚拟机
	 */
	private DevJvm getJvmInfo() throws UnknownHostException {
		DevJvm jvm = new DevJvm();
		Properties props = System.getProperties();
		jvm.setTotal(Runtime.getRuntime().totalMemory());
		jvm.setMax(Runtime.getRuntime().maxMemory());
		jvm.setFree(Runtime.getRuntime().freeMemory());
		jvm.setVersion(props.getProperty("java.version"));
		jvm.setHome(props.getProperty("java.home"));
		return jvm;
	}

	/**
	 * 设置磁盘信息
	 */
	private List<DevSysFile> getSysFiles(OperatingSystem os) {
		List<DevSysFile> sysFiles = new ArrayList();
		FileSystem fileSystem = os.getFileSystem();
		List<OSFileStore> fsArray = fileSystem.getFileStores();
		for (OSFileStore fs : fsArray) {
			long free = fs.getUsableSpace();
			long total = fs.getTotalSpace();
			long used = total - free;
			DevSysFile sysFile = new DevSysFile();
			sysFile.setDirName(fs.getMount());
			sysFile.setSysTypeName(fs.getType());
			sysFile.setTypeName(fs.getName());
			sysFile.setTotal(CommonUtil.convertFileSize(total));
			sysFile.setFree(CommonUtil.convertFileSize(free));
			sysFile.setUsed(CommonUtil.convertFileSize(used));
			sysFile.setUsage(Arith.mul(Arith.div(used, total, 4), 100));
			sysFiles.add(sysFile);
		}
		return sysFiles;
	}
	
	
	/**
	 * 设置运维统计
	 */
	private Devops getDevopsInfo()  {
	   	Map<String, Object> params = new HashMap<String, Object>();
	    Date t =DateUtils.getNowDate(); 	        
	    String graphDate = DateUtils.dateTime(t);
	    params.put("startTime", DateUtils.parseDate(graphDate + " 00:00:00"));
	    params.put("endTime", DateUtils.parseDate(graphDate + " 23:59:59"));

		Devops devops = new Devops();
		devops.setTotalHosts(hostMapper.countDevHostByDashboard());
		devops.setTotalAlarms(alarmMapper.countDevAlarm());
		devops.setUntreatedAlarms(alarmMapper.countDevAlarmUntreated());
		devops.setTodayAlarms(alarmMapper.countDevAlarmToday(params));
		devops.setTodayCollects(cpuLogMapper.countDevCpuLogToday(params));
		return devops;
	}

}
